const http=require('http');
const fs = require('fs');
const mysql = require('mysql');
const url = require('url');
const zlib = require('zlib');


http.createServer((req,res)=>{
  let {pathname,query} = url.parse(req.url,true);
  console.log(query.username);
  console.log(query.password);
  let db = mysql.createPool({host:'localhost',port:3306,user:'root',password:'zqy.123',database:'zqy'});
  switch (pathname) {
    case '/reg':
      if(!query.username){
        res.write('{"error":1,"msg":"username is required"}');
        res.end();
      }else if(!query.password){
        res.write('{"error":1,"msg":"password is required"}');
        res.end();
      }else{
        db.query(`select * from user_table where username='${query.username}'`,(err,data)=>{
          if(err){
            console.log(err);
            res.write('{"error":2,"msg":"database error"}');
            res.end();
          }else if(data.length>0){
            res.write('{"error":3,"msg":"user is exist"}');
            res.end();
          }else{
              db.query(`insert into user_table(id,username,password) values(0,'${query.username}','${query.password}')`,(error,data)=>{
                if(error){
                  res.write('{"error":2,"msg":"database error"}');
                  res.end();
                }else{
                  res.write('{"error":0,"msg":"regist success"}');
                  res.end();
                }
              });
          }
        });
      }
      break;
    case '/login':
    if(!query.username){
      res.write('{"error":1,"msg":"username is required"}');
      res.end();
    }else if(!query.password){
      res.write('{"error":1,"msg":"password is required"}');
      res.end();
    }else{
      db.query(`select * from user_table where username=${query.username}`,(err,data)=>{
        if(err){
          res.write('{"error":2,"msg":"database error"}');
          res.end();
        }else if(data[0].password!==query.password){
          res.write('{"error":4,"msg":"username or password is error"}');
          res.end();
        }else{
          res.write('{"error":0,"msg":"login success"}');
          res.end();
        }
      });
    }
      break;
    default:
      let rs = fs.createReadStream(`.\\${pathname}`);
      let gz = zlib.createGzip();
      res.setHeader('content-encoding','gzip');
      rs.pipe(gz).pipe(res);
      rs.on('error',err=>{
        res.writeHeader(404);
        res.write('Not Found');
        res.end();
      });
      rs.on('finish',()=> {
        console.log('传输完成！');
        res.end();
      });
  }
}).listen(8080);
